import pyttsx3
# import gtts
from pathlib import Path
import hashlib

def text_to_voice(text: str, is_man: bool = False) -> str:
    assert text and text.replace(' ',''), "文本不能为空"
    filename = hashlib.md5(text.encode()).hexdigest() + ".mp3"
    filepath = Path('voices') / Path(filename)
    if filepath.exists():
        return filename
    engine = pyttsx3.init()  # object creation
    engine.save_to_file(text, filepath.as_posix())
    engine.runAndWait()
    engine.stop()
    return filename

#
# def text_to_voice_google(text:str):
#     """
#     使用 google 的 api，需要能联网
#     :param text:
#     :return:
#     """
#     filename = hashlib.md5(text.encode()).hexdigest() + ".mp3"
#     root = Path('voices')
#     if not root.exists():
#         root.mkdir()
#     filepath =  root / Path(filename)
#
#     if filepath.exists():
#         return filename
#
#     tts = gtts.gTTS(text)
#     filename = hashlib.md5(text.encode()).hexdigest()
#     tts.save(filepath.as_posix())
#     return filename





if __name__ == '__main__':
    path = text_to_voice("Python七号，每天学习一个 Python 技巧")
    print(path)